
import turf from '../../../ext/turf';
import ProgressBar from '../ProgressBar/ProgressBar';
import arrChunk from '../arrChunk';

const pg = new ProgressBar('聚合多边形', 40);
let featuresLength = 0;
let completedIndex = 0;

function union(sourceGeoJson: any) {
    let resGeoJson: any;
    turf.featureEach(sourceGeoJson, function (currentFeature: any, featureIndex: number) {
        if (featureIndex === 0) {
            resGeoJson = currentFeature;
        } else {
            resGeoJson = turf.union(resGeoJson, currentFeature);
        }
        completedIndex++;
        pg.render({
            completed: completedIndex,
            total: featuresLength,
            description: '聚合多边形'
        });
    });

    return resGeoJson;
}

function unionGeoJson(geoJson: any) {
    const sourceGeoJson = turf.flatten(geoJson);
    featuresLength = sourceGeoJson.features.length;
    completedIndex = 0;

    const group = [];

    if (featuresLength > 200) {
        const chunkSize = Math.ceil(featuresLength / 10);
        const chunk = arrChunk(sourceGeoJson.features, chunkSize);
        for (let i = 0; i < chunk.length; i++) {
            group.push(chunk[i]);
        }
    } else {
        group.push(sourceGeoJson.features);
    }


    // 分组计算聚合图形
    const groupGeoJson = [];
    for (let i = 0; i < group.length; i++) {
        const collection = turf.featureCollection(group[i]);
        groupGeoJson.push(union(collection));
    }

    // 汇总聚合
    let sumGeoJson = union(turf.featureCollection(groupGeoJson));

    return turf.flatten(sumGeoJson);
}

export default unionGeoJson;
